<?php

namespace app\controller;

use support\Request;

class uploadController
{
    public function image(Request $request)
    {
        //
        $file = $request->file('file');
        if (!$file || !$file->isValid()) {
            return json(['code' => 1, 'msg' => 'file not found']);
        }

        //
        $ext = $file->getUploadExtension();
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
            return json(['errno'=>1,'msg'=>'图片格式不正确']);
        }

        //
        $upload_dir = "/upload/image/" . date("Ymd");
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir,0777,true);
        }

        //
        $name = date("YmdHis") . rand(100000,999999);
        $url = $upload_dir . "/". $name .".". $ext;
        try {
            $file->move(public_path(). $url);
            return json(['code' => 0, 'msg' => 'upload success','data'=>['src'=>$url]]);
        } catch (\Exception $e) {
            return json(['errno'=>1,'msg'=>$e->getMessage()]);
        }
    }

    public function file(Request $request)
    {
        //
        $file = $request->file('file');
        if (!$file || !$file->isValid()) {
            return json(['code' => 1, 'msg' => 'file not found']);
        }

        //
        $ext = $file->getUploadExtension();
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
            return json(['errno'=>1,'msg'=>'文件格式不正确']);
        }

        //
        $upload_dir = "/upload/file/" . date("Ymd");
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir,0777,true);
        }

        //
        $name = date("YmdHis") . rand(100000,999999);
        $url = $upload_dir . "/". $name .".". $ext;
        try {
            $file->move(public_path(). $url);
            return json(['code' => 0, 'msg' => 'upload success','data'=>['src'=>$url]]);
        } catch (\Exception $e) {
            return json(['errno'=>1,'msg'=>$e->getMessage()]);
        }
    }
}
